<template>
  <a-spin :spinning="loading" :tip="t('请稍后······')">
    <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <a-form-item :label="t('新密码')" v-bind="validateInfos.newPassword">
        <a-input-password
          v-model:value="modelRef.newPassword"
          :placeholder="t('请输入新密码')"
          allow-clear
          autocomplete="off"
        >
        </a-input-password>
      </a-form-item>
      <a-form-item
        :label="t('确认密码')"
        v-bind="validateInfos.confirmPassword"
      >
        <a-input-password
          v-model:value="modelRef.confirmPassword"
          :placeholder="t('请输入确认密码')"
          allow-clear
          autocomplete="off"
        >
        </a-input-password>
      </a-form-item>
    </a-form>
  </a-spin>
  <a-space style="float: right">
    <a-button type="primary" :loading="loading" @click="handleSubmit">
      {{ t("下一步") }}
    </a-button>
  </a-space>

  <div style="clear: both"></div>
</template>
<script lang="ts" setup>
import { resetPassword } from "@/api/auth";
import { FormRule } from "@/typing";
import { Form } from "ant-design-vue";
import { reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
interface Props {
  /**邮箱 */
  email: string;
}
const props = defineProps<Props>();
const emit = defineEmits(["cancel", "next"]);
const { t } = useI18n();
const modelRef = reactive({
  newPassword: null,
  confirmPassword: null,
});
const modelRule = reactive<FormRule<typeof modelRef>>({
  newPassword: [
    { required: true, message: () => t("请输入新密码"), trigger: "blur" },
  ],
  confirmPassword: [
    {
      required: true,
      message: () => t("请确认新密码"),
      validator(_rule, value) {
        if (value !== modelRef.newPassword) {
          return Promise.reject(t("两次输入的密码不一致"));
        } else {
          return Promise.resolve();
        }
      },
      trigger: "blur",
    },
  ],
});
const { validate, validateInfos, resetFields } = Form.useForm(
  modelRef,
  modelRule
);
const loading = ref(false);
// 重置密码
const handleSubmit = async () => {
  const valid = await validate();
  if (!valid) return;
  loading.value = true;
  const { success } = await resetPassword({
    email: props.email,
    password: modelRef.newPassword,
  });
  loading.value = false;
  if (success) {
    emit("next");
  }
};
defineExpose({ resetFields });
</script>
